﻿using MediatR;
using SheepCultivation.Common.Domain.Beginning;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;
using Yitter.IdGenerator;

namespace SheepCultivation.API.AddliCation.BeginningW
{
    public class ProgenyPeriodicCreateHandler : IRequestHandler<ProgenyPeriodicCreateCommon, Result>
    {
        public readonly IBaseRepository<ProgenyPeriodic> ProgenyPeriodicRepository;
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;

        public ProgenyPeriodicCreateHandler(IBaseRepository<ProgenyPeriodic> progenyPeriodicRepository, IBaseRepository<BasicInformation> basicInformationRepository)
        {
            ProgenyPeriodicRepository = progenyPeriodicRepository;
            BasicInformationRepository = basicInformationRepository;
        }

        public async Task<Result> Handle(ProgenyPeriodicCreateCommon request, CancellationToken cancellationToken)
        {
            var res = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var num = new DocumentnumberDto();
                var list = new ProgenyPeriodic()
                {
                    ProgenyPeriodicReceiptNumber = DateTime.Now.ToString("yyyyMMdd")+num.Num,
                    ProgenyPeriodicPeriodicDate = request.ProgenyPeriodicPeriodicDate,
                    BreedingSheepArchiveId = request.BreedingSheepArchiveId,
                    ProgenyPeriodicSavNumber = YitIdHelper.NextId().ToString(),
                    BuildingId = request.BuildingId,
                    ColumnsId = request.ColumnsId,
                    ProgenyPeriodicStage = request.ProgenyPeriodicStage,
                    ProgenyPeriodicNumber = request.ProgenyPeriodicNumber,
                    ProgenyPeriodicWeight=request.ProgenyPeriodicWeight,
                    Remark = request.Remark,
            };
                 num.Num++;
                ProgenyPeriodicRepository.Add(list);
                var list1 = BasicInformationRepository.GetAll().Where(x => x.BreedingSheepArchiveId == request.BreedingSheepArchiveId).ToList();
                foreach (var item in list1)
                {
                    item.BuildingId = request.BuildingId;
                    item.ColumnsId = request.ColumnsId;
                    item.SheepStatus = 1;
                    BasicInformationRepository.Update(item);
                }
                res.Code = (int)CommonEnumCode.success;
                res.Msg = "后裔期初表新增";
            }
            catch (Exception ex)
            {

            }
            return res;
        }
    }
}
